package com.perfectoMobile.utils;



import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;


import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;




public class XPathParser {

	private XPath 		_xpath 	= null	;
	private Document 	_doc 	= null	;
	
	public XPathParser (String xml)
	{
		ByteArrayInputStream inputStream = null ;
	    
		try {
			
			inputStream = new ByteArrayInputStream(xml.getBytes("UTF8"));
			
		} catch (UnsupportedEncodingException e) {


		}

        try
        {
               DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
               domFactory.setNamespaceAware(true);
               DocumentBuilder builder = domFactory.newDocumentBuilder();
               _doc = builder.parse(inputStream) ;
               XPathFactory factory = XPathFactory.newInstance();
               _xpath = factory.newXPath();
        }
        
        catch (SAXException e) {

        	
        } catch (IOException e) {


        } catch (ParserConfigurationException e) {

        }
	}
	
	public NodeList getNodeList(String exp)
	{
		if (_xpath!=null)
		{
			try {
				Object nodeList = _xpath.evaluate(exp, _doc, XPathConstants.NODESET);
				if (nodeList!=null)
					return (NodeList)nodeList;
			} catch (XPathExpressionException e) {
				
			}
		}
		return null;
	}
	
	public Node getNode(String exp)
	{
		if (_xpath!=null)
		{
			try {
				Object node = _xpath.evaluate(exp, _doc, XPathConstants.NODE);
				if (node!=null)
					return (Node)node;
			} catch (XPathExpressionException e) {
				
			}
		}
		return null;
	}
	
	public String getString(String exp)
	{
		if (_xpath!=null)
		{
			try {
				Object node = _xpath.evaluate(exp, _doc, XPathConstants.STRING);
				if (node!=null)
					return (String)node;
			} catch (XPathExpressionException e) {

			}
		}
		return null;
	}
	

}
